package com.karaku.karaku_collector.util;

import android.app.ActivityManager;
import android.content.Context;
import android.text.TextUtils;

import com.karaku.karaku_collector.App;

import java.util.List;

/**
 * Created by guoping on 2017/4/26.
 */

public class ProcessUtil {

    private static String sProcessName;

    public static boolean isMainProcess() {
        return getProcessName().equals(App.getInstance().getPackageName());
    }

    public static boolean hasMainProcess() {
        ActivityManager activityManager = (ActivityManager) App.getInstance().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> allProcess = activityManager.getRunningAppProcesses();
        if (allProcess != null) {
            for (ActivityManager.RunningAppProcessInfo aInfo : allProcess) {
                if (aInfo.pid == android.os.Process.myPid()) {
                    if (App.getInstance().getPackageName().equals(aInfo.processName)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private static String getProcessName() {
        if (TextUtils.isEmpty(sProcessName)) {
            ActivityManager activityManager = (ActivityManager) App.getInstance().getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> allProcess = activityManager.getRunningAppProcesses();
            if (allProcess != null) {
                for (ActivityManager.RunningAppProcessInfo aInfo : allProcess) {
                    if (aInfo.pid == android.os.Process.myPid()) {
                        sProcessName = aInfo.processName;
                    }
                }
            }
        }
        return sProcessName;
    }
}
